import React from 'react';
import Tree from '../../components/tree';
import { Row, Col, Cascader, Input, Button, Card, Modal, message, Form, Checkbox,Message } from 'antd';
import { selectAllRole, addRole, getMenuByRoleId, selectAllMenu, updateRole, delRole,   } from '../../services/api';

import { formatCascader } from '../../common/common'
const confirm = Modal.confirm;

@Form.create()
class Manage extends React.Component {

	state = {
		deptTree: [], //区域树结构
    chooseData: [{fid:1,name: '123'},{fid:2,name: '456'}],
    roleArr: [],
		changeId: '',
		menuArr: []
	};

	componentDidMount() {
		this.getAllRoleAjax();
		this.selectAllMenuAjax();
	}

	async selectAllMenuAjax() {
		const response = await selectAllMenu();
		if (response.code  === 200) {
			this.setState({
				menuArr: response.data
			})
		} else {
			message.error(response.msg);
		}
	}

	//获取区域信息
	async getAllRoleAjax() {
		const response = await selectAllRole();
		if (response.code === 200) {
			this.setState({ deptTree: response.data })
		} else {
			response.msg && message.error(response.msg);
		}
	}

	//获取区域详细信息
	async getDeptDetail(fid) {
		const response = await getMenuByRoleId(fid);
		if (response.code === 200) {
			this.setState({ roleArr: response.data, isShow: true },()=>{
				this.compareList();
			})
		} else {
			response.msg && message.error(response.msg);
		}
	}

	// 比对选中项
	compareList() {
		for (let obj of this.state.roleArr) {
			for (let val of this.state.menuArr) {
				if (obj.fId === val.fId) {
					val.checked = true;
					break;
				}	
			}
		}
		this.setState({
			menuArr: this.state.menuArr
		});
	}
	/**
	 * 获取左侧角色树当前选中的角色
	*/
	selectNode = (val) => {
    // 使用递归找到选中对象
		let obj = this.findObj(this.state.deptTree, val[0]);
		if (!val[0]) {
			this.setState({
				obj: null,
				fid: '',
				roleArr: []
			});
			return;
		}
		this.setState({
      fid: val[0],
			obj: obj,
		});
		for (let val of this.state.menuArr) {
			val.checked = false;
		}
		this.setState({
			menuArr: this.state.menuArr
		}, ()=> {
			this.getDeptDetail(val[0]);
		});
  }
  
  findObj (arr, fId) {
    for (let obj of arr) {
      if (obj.fId === fId) {
        return obj
      }
      if (obj.children && obj.children.length > 0) {
        return this.findObj(obj.children, fId);
      }    
    }
  }
	/**
	 * 获取右侧权限树已选中权限（id）
	*/
	checkNode = (val) => {
	}
	
	hideModal= () => {
		if (this.state.userLoading) {
			message.warning('正在处理中,请稍后')
			return;
		}
		this.setState({
			visible: false,
			name: '',
			username: '',
			password: '',
		});
		this.props.form.resetFields();
	}

	// 提交用户列表 信息修改或增加的方法
	handleSubmit = () => {
		this.props.form.validateFields((err, values) => {
      if (err) {
				return;
			}
			// values 是提交的数据
			this.setState({userLoading: true});
			if (this.state.obj) {
				let arr = [];
				for (let obj of this.state.roleArr) {
					arr.push(obj.fId)
				}
				updateRole({
					fId: this.state.obj.fId,
					fRoleName: values.username.Trim(),
					rolePCode: this.state.obj.rolePCode,
					listMenu: arr
				})
				.then((data)=>{
					this.setState({userLoading: false});
					if (data.code === 200) {
						this.setState({
							visible: false,
							// 重置文本框中的内容
							name: '',
							username: '',
							password: ''
						});
						this.props.form.resetFields();
						this.setState({obj: null});
						this.getAllRoleAjax();
						Message.success('');
					} else {
						message.error(data.msg);
					}
				})
				return;
			}
			addRole({
				listMenu: [],
				roleName: values.username.Trim(),
				rolePCode: values.fatherId?values.fatherId[values.fatherId.length-1]:undefined
			})
			.then((data)=>{
				this.setState({userLoading: false});
				if (data.code === 200) {
					this.setState({
						visible: false,
						// 重置文本框中的内容
						name: '',
						username: '',
						password: ''
					});
					this.props.form.resetFields();
					this.setState({obj: null});
					this.getAllRoleAjax();
					Message.success('')
				} else {
					message.error(data.msg);
				}
			})
		
		});
	}


	// 删除区域详情
	deleteDetail = () => {
		confirm({
      title: '提示',
      content: `您确认要删除 ${this.state.obj.fRoleName} 的角色详情吗?`,
      okText: '确认',
      cancelText: '取消',
      onOk: ()=> {
        // 一个loading的处理
        this.setState({ delLoading: true });
        return new Promise((resolve, reject)=> {
					delRole(this.state.obj.fId)
					.then((data)=>{
						this.setState({ delLoading: false });
						if (data.code === 200) {
							this.setState({obj: null});
							this.selectAllMenuAjax();
						  this.getAllRoleAjax();
							Message.success('删除成功');
						} else {
							message.error(data.msg);
						}
					})
          resolve(); // 成功的返回
        }).catch(() => console.log('删除出错'));
      },
      onCancel:()=> {
        if (this.state.delLoading) {
          message.warning('处理中,请稍后');
          return new Promise((resolve, reject)=> {
            while (!this.state.delLoading) {
              resolve();
            }
          })
        }
      },
    });	
	}	
	// 新增区域的提交
	handleSubmitArea = () => {
		this.props.form.validateFields((err, values) => {
      if (err) {
				return;
			}
			// values 是提交的数据
			this.setState({areaLoading: true});
			// 接口调用
			// 成功之后的处理 1. 关闭loading 2. 刷新当前页的数据, 如果是新增则跳转第一页 3. 关闭modal
			this.setState({areaLoading: false});
			this.setState({
				addArea: false
			});
			this.props.form.resetFields();
    });
	}
	checkTextArea = (rule, value, callback) => {
		if (value && value.trim().length>100 ) {
			callback('字数不能超过100');
			return;
		}
		callback();
	}
	// 关闭新增区域
	hideModalArea = () => {
		if (this.state.userLoading) {
			message.warning('正在处理中,请稍后')
			return;
		}
		this.setState({
			visible: false,
			name: '',
			username: '',
			password: '',
		});
		this.props.form.resetFields();
  }
  // 权限列表全选
  checkAll = (e) => {
		const checkStatus = e.target.checked;
    for (let obj of this.state.menuArr) {
      obj.checked = checkStatus;
    }
    this.setState({
      allCheck: checkStatus,
      menuArr: this.state.menuArr
    });
  } 

  // 选择权限方法
  chooseRole (e,fId)  {
    let checkStatus = e.target.checked;
    for (let obj of this.state.menuArr) {
      if (obj.fId === fId) {
        obj.checked = checkStatus;
        break;
      }
    }
    this.setState({
      roleArr: this.state.roleArr
    });
  }
  // 保存权限
  async saveRole() {
		let arr = [];
		for (let obj of this.state.menuArr) {
			if (obj.checked) {
				arr.push(obj.fId);
			}
		}
		const response = await updateRole({fId: this.state.obj.fId, listMenu: arr});
		if (response.code === 200) {
			this.getDeptDetail(this.state.obj.fId);
			Message.success('保存成功');
		} else {
			message.error(response.msg);
		}
  }
  // 打开修改窗口
  updateRole() {
    if (!this.state.obj) {
      message.warning('请选择一个角色');
      return;
    }
    this.setState({
			visible: true,
    });
  }

	render() {
		const { getFieldDecorator } = this.props.form;
		const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
		};
		return (
			<Row>
				<Col span={6}>
					<Card title={<Row type="flex" justify="space-between">
												<Col>
													角色列表
												</Col>
												<Col>
													<Button type="primary" size="small" style={{marginRight: 20}} onClick={()=>this.setState({visible: true, obj: null})}>新增</Button>
                          <Button type="primary" size="small" onClick={()=>{this.updateRole()}}>修改</Button>
												</Col>
											</Row>}>
						<Tree data={this.state.deptTree} name="fName" id="fId" selectNode={this.selectNode} />
					</Card>
				</Col>
				<Col span={17}>
					{this.state.obj ? 
					<Card 
						title={<Row type="flex" justify="space-between">
										<Col>
											角色详情
										</Col>
										<Col>
												<Button type="primary" size="small" style={{marginRight: 20}} onClick={()=>this.saveRole()}>保存</Button>
												<Button type="danger" size="small" style={{marginRight: 20}} onClick={this.deleteDetail}>删除</Button>
										</Col>
									</Row>}
			 			style={{ width: '100%' }}
					>
						<Row style={{marginBottom: 10}}>
							<Col span={6}>
								<Row>
                  <span>角色名称：{this.state.obj.fRoleName}</span>
								</Row>
							</Col>
						</Row>
            <Card title={<Row type="flex" justify="space-between">
										<Col>
											权限列表
										</Col>
										<Col>
												<Checkbox checked={this.state.allCheck} onChange={(e)=>this.checkAll(e)}>全选</Checkbox>
										</Col>
									</Row>}
            >
              <div>
                {this.state.menuArr.map((data)=>{
                  return (
                    <Checkbox key={data.fid} checked={data.checked} onChange={(e)=>this.chooseRole(e,data.fId)}>{data.fMenuName}</Checkbox> 
                  )
                })}
              </div>
            </Card>
					</Card> : null} 
				</Col>
				<Modal
          title={this.state.obj?'修改角色':'新增角色'}
					visible={this.state.visible}
					confirmLoading={this.state.userLoading}
          onOk={this.handleSubmit}
          onCancel={this.hideModal}
          okText="确认"
					cancelText="取消"
					maskClosable={false}
        >
					<Form>
						<Form.Item
							{...formItemLayout}
							label="角色名称"
						>
							{getFieldDecorator('username', {
								initialValue: this.state.obj?this.state.obj.fRoleName: '',
								rules: [{
									required: true, message: '请输入角色名',
									whitespace: true, message: '请输入角色名'
								}],
							})(
								<Input maxLength={'20'} placeholder="请输入"/>
							)}
						</Form.Item>
						{this.state.obj? null:
						<Form.Item
							{...formItemLayout}
							label="父级"
						>
							{getFieldDecorator('fatherId', {
								initialValue:this.state.obj?this.state.obj.rolePCode.split(','): '',
							})(
								<Cascader style={{width: '100%'}} changeOnSelect options={formatCascader(this.state.deptTree, 'roleCode', 'fRoleName', 'children')} placeholder="请选择..."/>
							)}
						</Form.Item>
						}
					</Form>
        </Modal>
			</Row>
		);
	}

}

export default Manage;